//
//  HYOUHotViewController.m
//  BestGift
//
//  Created by 温晓宇 on 15/12/29.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "HYOUHotViewController.h"
#import "HYOUHotView.h"
#import "HYOUHotWebViewController.h"
@interface HYOUHotViewController ()<HYOUHotViewDelegate>

@property(nonatomic, retain) HYOUHotView *hot;

@property(nonatomic, retain) NSMutableArray *allArray;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉

@end

@implementation HYOUHotViewController

-(void)dealloc{
    [_hot release];
    [_allArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = RGBA(242, 242, 242, 1);
    
    self.navigationItem.title = @"热门";
    
    UIImage *image = [[UIImage imageNamed:@"iconfont-jycxun"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    
    self.hot = [[HYOUHotView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
//    self.hot.backgroundColor = [UIColor whiteColor];
    self.hot.delegate = self;
    [self.view addSubview:self.hot];
    [_hot release];
    
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    /*************热门解析***************/
    self.allArray = [NSMutableArray array];
//    NSString *hot = @"http://api.liwushuo.com/v2/items?limit=20&offset=0&gender=2&generation=1";
//    dispatch_async(dispatch_get_main_queue(), ^{
//    [AppTools finalAFNWithURLString:hot parameters:nil successAFNBlock:^(id resuposeObject) {
//        NSMutableDictionary *bigDic = resuposeObject;
//        NSMutableDictionary *data = [bigDic objectForKey:@"data"];
//        NSMutableArray *items = [data objectForKey:@"items"];
//        for (NSDictionary *dic in items) {
//            NSDictionary *min = [dic objectForKey:@"data"];
//            HYOUHotModel *hot  = [[HYOUHotModel alloc]init];
//            [hot setValuesForKeysWithDictionary:min];
//            [self.allArray addObject:hot];
//            [hot release];
//        }
//        self.hot.allArray = self.allArray;
//        [self.hot.myCollectionView reloadData];
////        [self.hot.myCollectionView reloadInputViews];
//    }];
//});
    
}
#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block HYOUHotViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.hot.myCollectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.hot.myCollectionView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block HYOUHotViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.hot.myCollectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage += 20;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}





#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    //    NSString *url_string = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/friends.json?uid=5626008324&access_token=2.00klJkIGGZulFC50e2f524e40S8nlw&cursor=%ld&count=2",nextCursor];
    
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items?generation=1&gender=2&limit=20&offset=%ld",nextCursor];
//
//    NSLog(@" page = %ld\n url = %@", self.nextPage, url_string);
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.allArray removeAllObjects];
        }
        
                NSMutableDictionary *bigDic = responseObject;
                NSMutableDictionary *data = [bigDic objectForKey:@"data"];
                NSMutableArray *items = [data objectForKey:@"items"];
                for (NSDictionary *dic in items) {
                    NSDictionary *min = [dic objectForKey:@"data"];
                    HYOUHotModel *hot  = [[HYOUHotModel alloc]init];
                    [hot setValuesForKeysWithDictionary:min];
                    [self.allArray addObject:hot];
                    [hot release];
                }
                self.hot.allArray = self.allArray;
//                [self.hot.myCollectionView reloadData];
        
        
        [self.hot.myCollectionView footerEndRefreshing];
        [self.hot.myCollectionView headerEndRefreshing];
        [self.hot.myCollectionView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}
-(void)hotDetail:(NSString *)url Image:(NSString *)image title:(NSString *)title{
    HYOUHotWebViewController *web = [[HYOUHotWebViewController alloc] init];
    web.url = url;
    web.image = image;
    web.name = title;
    [self.navigationController pushViewController:web animated:YES];
}

-(void)searchAction:(UIBarButtonItem *)btn{
    HYOUSearchViewController *search = [[HYOUSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
